﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Text;

using SkyReader.TransferDataService;
using System.IO.IsolatedStorage;
namespace SkyReader
{
    public partial class LocalBooks : PhoneApplicationPage
    {
        private string bookContent;
        public LocalBooks()
        {
            InitializeComponent();
            
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("1. Download Windows Phone 7 transfer tool from http://www.google.com");
            sb.AppendLine();
            sb.AppendLine();
            sb.Append("2. Run it on your computer and then click Start Service.");
            sb.AppendLine();
            sb.AppendLine();
            sb.Append("3. Click the following icon to download books from your computer.");

            this.lblInformation.Text = sb.ToString();

            // Set default values
            this.lstFontSize.SelectedIndex = 2;
            this.lstFontFamily.SelectedIndex = 7;
        }

        private void lstFontSize_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.lblPreview != null)
            {
                ListPicker listPicker = sender as ListPicker;
                this.lblPreview.FontSize = Convert.ToDouble(listPicker.SelectedItem.ToString());
            }
        }

        private void lstFontFamily_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.lblPreview != null)
            {
                ListPicker listPicker = sender as ListPicker;
                this.lblPreview.FontFamily = new FontFamily(listPicker.SelectedItem.ToString());
            }
        }


        private void btnDownload_Click(object sender, EventArgs e)
        {
            LoadPanel.Visibility = System.Windows.Visibility.Visible;
            ContentPanel.Visibility = System.Windows.Visibility.Collapsed;
            TransferDataServiceClient client = new TransferDataServiceClient();
            client.GetFielsCompleted += new EventHandler<GetFielsCompletedEventArgs>(client_GetFielsCompleted);
            client.GetFielsAsync("*.txt");
        }

        private void client_GetFielsCompleted(object sender, GetFielsCompletedEventArgs e)
        {
            lblInformation.Visibility = System.Windows.Visibility.Collapsed;
            lstFile.Visibility = System.Windows.Visibility.Visible;
            List<TFileInfo> fileList = e.Result;
            lstFile.ItemsSource = fileList;

            LoadPanel.Visibility = System.Windows.Visibility.Collapsed;
            ContentPanel.Visibility = System.Windows.Visibility.Visible;
        }

        private void btnDownloadFile_Click(object sender, RoutedEventArgs e)
        {
            LoadPanel.Visibility = System.Windows.Visibility.Visible;
            ContentPanel.Visibility = System.Windows.Visibility.Collapsed;

            Button button = sender as Button;
            string fileName = button.Tag.ToString();

            string title;
            int lastIndex = fileName.LastIndexOf('.');
            title = fileName.Substring(0, lastIndex);
            this.txtTitle.Text = title;


            TransferDataServiceClient client = new TransferDataServiceClient();
            client.TransferFileCompleted += new EventHandler<TransferFileCompletedEventArgs>(client_TransferFileCompleted);
            client.TransferFileAsync(fileName, 0, -1);
        }

        private void client_TransferFileCompleted(object sender, TransferFileCompletedEventArgs e)
        {
            // Get book content
            byte[] buffer = e.Result;
            bookContent = Encoding.UTF8.GetString(buffer, 0, buffer.Length);

            this.lblPreview.FontFamily = new System.Windows.Media.FontFamily(this.lstFontFamily.SelectedItem.ToString());
            this.lblPreview.FontSize = Convert.ToDouble(this.lstFontSize.SelectedItem);

            LoadPanel.Visibility = System.Windows.Visibility.Collapsed;
            SavePanel.Visibility = System.Windows.Visibility.Visible;
        }

        
        private string bookId;
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            bookId = "BOOK" + this.txtTitle.Text.Trim();
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            if (settings.Contains(bookId))
            {
                MessageBoxResult result = MessageBox.Show("There is already a book with the same title in the book shelf, are you sure you want to replace this book?", "Replace book?", MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.Cancel)
                {
                    return;
                }
            }

            // show waiting for 
            SavePanel.Visibility = System.Windows.Visibility.Collapsed;
            LoadPanel.Visibility = System.Windows.Visibility.Visible;
            lblLoading.Text = "Saving and creating page index ...";

            Deployment.Current.Dispatcher.BeginInvoke(SaveBook);
        }

        private void SaveBook()
        {
            //progBar.IsIndeterminate = false;

            Book book = null;
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            if (settings.Contains(bookId))
            {
                book = settings[bookId] as Book;
            }
            else
            {
                book = book = new Book()
                {
                    Title = this.txtTitle.Text.Trim(),
                    FileName = string.Format("{0}.txt", Guid.NewGuid()),
                    CurrentPage = 1,
                    MarkList = new List<Mark>()
                };
            }

            settings[bookId] = book;
            settings.Save();
            // 2. save book into iso folder 
            IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication();
            if (isoFile.FileExists(book.FileName))
            {
                isoFile.DeleteFile(book.FileName);
            }

            using (IsolatedStorageFileStream isoFs = isoFile.CreateFile(book.FileName))
            {
                byte[] content = Encoding.UTF8.GetBytes(bookContent);
                isoFs.Write(content, 0, content.Length);
                book.DateCreated = DateTime.Now;
                book.Size = string.Format("{0:N} KB", content.Length / 1024);
            }

            // 3. generate page index of the book
            book.PageDict = new Dictionary<int, int>();
            book.FontSize = Convert.ToDouble(this.lstFontSize.SelectedItem.ToString());
            book.FontFamily = this.lstFontFamily.SelectedItem.ToString();

            string overflowContent = string.Empty;
            int point = 0;
            int pagePoint = 0;
            int currentPage = 0;

            TextBlock textBlock = new TextBlock()
            {
                TextWrapping = TextWrapping.Wrap,
                FontSize = book.FontSize,
                FontFamily = new FontFamily(book.FontFamily),
                Width = SystemConst.PAGE_WIDTH,
                Height = SystemConst.PAGE_HIGHT
            };



            PageBuilder page = new PageBuilder(textBlock);
            while (point != bookContent.Length)
            {
                string line = string.Empty;
                if (overflowContent.Length == 0)
                {
                    if (point + 100 < bookContent.Length)
                    {
                        line = bookContent.Substring(point, 100);
                    }
                    else
                    {
                        line = bookContent.Substring(point);
                    }

                    point = point + 100;
                    if (point > bookContent.Length)
                    {
                        point = bookContent.Length;
                    }
                }
                else
                {
                    line = overflowContent;
                }

                overflowContent = page.Append(line);
                if (overflowContent.Length != 0)
                {
                    currentPage = currentPage + 1;
                    book.PageDict.Add(currentPage, pagePoint);
                    pagePoint = pagePoint + page.Content.Length;
                    page = new PageBuilder(textBlock);
                }
            }
            currentPage = currentPage + 1;
            book.PageDict.Add(currentPage, pagePoint);

            MessageBox.Show("This book has been added to the book shelf.", "Save successful", MessageBoxButton.OK);

            LoadPanel.Visibility = System.Windows.Visibility.Collapsed;
            ContentPanel.Visibility = System.Windows.Visibility.Visible;
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            ContentPanel.Visibility = System.Windows.Visibility.Visible;
            SavePanel.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void btnHome_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Bookshelf.xaml", UriKind.Relative));
        }
    }
}